// Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.

// 弹性伸缩策略查询服务
package policy

import (
	"encoding/json"
	"fleetmanager/api/errors"
	"fleetmanager/api/model/policy"
	"fleetmanager/api/params"
	"fleetmanager/db/dao"
	"fmt"
	"net/http"
)

func (s *Service) transPolicy(pd dao.ScalingPolicy) policy.ScalingPolicy {
	p := policy.ScalingPolicy{
		Id:            pd.Id,
		Name:          pd.Name,
		PolicyType:    pd.PolicyType,
		ScalingTarget: pd.ScalingTarget,
		State:         pd.State,
	}
	err := json.Unmarshal([]byte(pd.TargetBasedConfiguration), &p.TargetBasedConfiguration)
	if err != nil {
		s.Logger.Warn("trans policy error: %v", err)
	}

	return p
}

func (s *Service) transPolicies(pds []dao.ScalingPolicy) []policy.ScalingPolicy {
	policies := make([]policy.ScalingPolicy, len(pds))
	for i, pd := range pds {
		policies[i] = s.transPolicy(pd)
	}
	return policies
}

func (s *Service) checkOffsetLimit(count int64, offset int, limit int) *errors.CodedError {
	if int64(offset*limit) >= count {
		return errors.NewErrorF(errors.InvalidParameterValue, " offset and limit over total count")
	}
	return nil
}

// List 查询fleet policy列表
func (s *Service) List(offset int, limit int) (code int, rsp []byte, e *errors.CodedError) {
	projectId := s.Ctx.Input.Param(params.ProjectId)
	total, count, policyList, err := dao.GetScalingPolicyStorage().ListAllPolicy(offset, limit, projectId)
	if err != nil {
		return 0, nil, errors.NewErrorF(errors.DBError, fmt.Sprintf("error:%+v", err))
	}
	listRsp := &policy.ListResponse{
		TotalCount:      int(total),
		Count:           int(count),
		ScalingPolicies: s.transPolicies(policyList),
	}
	rsp, err = json.Marshal(listRsp)
	if err != nil {
		return 0, nil, errors.NewErrorF(errors.ServerInternalError, fmt.Sprintf("error:%+v", err))
	}
	return http.StatusOK, rsp, nil
}

func (s *Service) GetPolicy(policyId string) (*policy.AssociatedPolicyOfFleet, *errors.CodedError) {
	policyDB, err := dao.GetScalingPolicyStorage().Get(dao.Filters{"Id": policyId})
	if err != nil {
		s.Logger.Error("get policy [%s] error:%+v", policyId, err)
		return nil, errors.NewErrorF(errors.DBError, fmt.Sprintf("error:%+v", err))
	}
	config := policy.TargetBasedConfiguration{}
	if err := json.Unmarshal([]byte(policyDB.TargetBasedConfiguration), &config); err != nil {
		s.Logger.Error("json unmarshal target base configuration error:%+v", err)
		return nil, errors.NewErrorF(errors.ServerInternalError, fmt.Sprintf("error:%+v", err))
	}
	p := policy.AssociatedPolicyOfFleet{
		Id:                       policyDB.Id,
		Name:                     policyDB.Name,
		PolicyType:               policyDB.PolicyType,
		TargetBasedConfiguration: config,
	}
	return &p, nil
}
